package com.ujiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujiuye.mapper.MenuMapper;
import com.ujiuye.mapper.RoleMapper;
import com.ujiuye.mapper.UserMapper;
import com.ujiuye.pojo.Menu;
import com.ujiuye.pojo.Role;
import com.ujiuye.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name",name);
        //通过用户名查询到该用户 在通过用户id去查看该用户有什么权限和角色
        User user = userMapper.selectOne(userQueryWrapper);
         //查询到该用户属于什么角色
        List<Role> roleList = roleMapper.selectRoleCodesByUserId(user.getId());
         //查询到该用户所有权限
        List<Menu> menuList = menuMapper.selectMenuPermsByUserId(user.getId());
          //将所有的权限和角色都放入集合中
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (Role role : roleList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleCode()));
        }
        for (Menu menu : menuList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(menu.getPerms()));
        }

        return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),grantedAuthorityList);
    }
}
